package com.hnhczh.alipaydemo.demos.web.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
//import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayDataDataserviceBillDownloadurlQueryModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.hnhczh.alipaydemo.demos.web.config.DataConfig;
import com.hnhczh.alipaydemo.demos.web.entity.AliPayParam;
import com.hnhczh.alipaydemo.demos.web.entity.R;
import com.hnhczh.alipaydemo.demos.web.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

/**
 * description:
 * date: 2022/9/14 15:46
 * author: cyx
 */
@Slf4j
@Service
public class ZfbService {

    @Resource
    private DataConfig dataConfig;

    @Resource
    private AlipayClient alipayClient;


    public String orderPay(AliPayParam aliPayParam) {
        String orderId = aliPayParam.getOrderId();
        String goodsName = aliPayParam.getGoodsName();
        BigDecimal fee = aliPayParam.getFee();

        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl(dataConfig.getZfbReturnUrl());
        alipayRequest.setNotifyUrl(dataConfig.getZfbNotifyUrl()); //在公共参数中设置回跳和通知地址
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", orderId);
        jsonObject.put("total_amount", fee);
        jsonObject.put("subject", goodsName);
//        jsonObject.put("product_code", "QUICK_WAP_WAY");
        jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizContent(jsonObject.toString()); //填充业务参数

        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        log.info(JSONObject.toJSONString(form));
        return form;
    }

    public String orderPayNotify(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            log.info(valueStr);
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCertCheckV1(params, dataConfig.getZfbAlipayPublicCertPath(), "UTF-8", "RSA2");
//        boolean signVerified = AlipaySignature.rsaCheckV1(params, dataConfig.getZfbAlipayPublicKey(), "UTF-8", "RSA2");
        if (signVerified) {
            //验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            Long orderId = StringUtils.toLong(params.get("out_trade_no"));


            Map<String, Object> payMap = null;

            Map<String, Object> map = new HashMap<>();
            map.put("orderId", orderId);
        } else {
            //验签失败则记录异常日志，并在response中返回failure.
        }
        return null;
    }

    //
//    /**
//     * 支付宝退款 V3
//     *
//     * @param param
//     * @throws Exception
//     */
//    public void refund(Map<String, Object> param) throws Exception {
//        String bizId = StringUtils.chgNull(param.get("bizId"));
//        BigDecimal payFee = new BigDecimal(StringUtils.chgNull(param.get("payFee")));
//        String refundId = StringUtils.chgNull(param.get("refundId"));
//        BigDecimal refundFee = new BigDecimal(StringUtils.chgNull(param.get("refundFee")));
//
//        JSONObject data = new JSONObject();
//        //订单号
//        data.put("out_trade_no", bizId);
//        //退款金额
//        data.put("refund_amount", payFee);
//        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();//创建API对应的request类
//        request.setBizContent(data.toString()); //设置业务参数
//        AlipayTradeRefundResponse response = alipayClient.execute(request);//通过alipayClient调用API，获得对应的response类
//        System.out.print(response.getBody());
//        //根据response中的结果继续业务逻辑处理
//    }
//
    public void testOrderPay(Map<String, Object> param, HttpServletResponse response) throws IOException {
        String orderId = StringUtils.chgNull(param.get("orderId"));
        String goodsName = StringUtils.chgNull(param.get("goodsName"));
        BigDecimal fee = new BigDecimal(StringUtils.chgNull(param.get("fee")));
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl(dataConfig.getZfbReturnUrl());
        alipayRequest.setNotifyUrl(dataConfig.getZfbNotifyUrl()); //在公共参数中设置回跳和通知地址
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", orderId);
        jsonObject.put("total_amount", fee);
        jsonObject.put("subject", goodsName);
        jsonObject.put("product_code", "QUICK_WAP_WAY");
        alipayRequest.setBizContent(jsonObject.toString()); //填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
            response.setContentType("text/html;charset=" + "UTF-8");
            response.getWriter().write(form); //直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
            log.info(JSONObject.toJSONString(form));
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
    }


    public R<String> searchOrder(String orderId) throws AlipayApiException {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo(orderId);
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
            return R.ok(response.getBody());
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
            return R.fail("调用失败");
        }
    }

    public R<String> downloadOrder(HttpServletResponse httpServletResponse) throws AlipayApiException {
        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
        AlipayDataDataserviceBillDownloadurlQueryModel model = new AlipayDataDataserviceBillDownloadurlQueryModel();
        //model.setSmid("2088123412341234");
        model.setBillType("trade");
        model.setBillDate("2024-07-02");
        request.setBizModel(model);
        AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
            return R.ok(response.getBillDownloadUrl());
        } else {
            System.out.println("调用失败");
            return R.fail("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
    }


//
//    public Map<String, Object> createOrderMessage(Long orderId){
//        Map<String, Object> message = new HashMap<>();
//        message.put("groupName", "wxGroup");
//        message.put("topic", "sagaCreateConsume");
//        message.put("tag", "all");
//        Map<String, Object> map = new HashMap<>();
//        map.put("key" + UUID.randomUUID(), "pay_success_" + orderId);
//        map.put("code", "nowPaySuccess");
//        map.put("bizId", orderId);
//        map.put("objectId",1);
//        Map<String, Object> msg = new HashMap<>();
//        msg.put("orderId", orderId);
//        map.put("message",msg);
//        message.put("messages", map);
//        return message;
//    }

}
